<template>
  <div class="root">
    <!-- 头部区域 - 包含头像和基本信息标题 -->
    <div class="header">
      <div class="avatar-container" @click="openAvatarUpload">
        <img v-if="baseInfo.avatar" class="head-icon" :src="baseInfo.avatar" alt="用户头像" />
        <div v-else class="avatar-placeholder">
          <i class="el-icon-user"></i>
        </div>
        <div class="avatar-upload-overlay">
          <i class="el-icon-camera"></i>
          <span>更换头像</span>
        </div>
      </div>
      <span class="baseInfo">基本信息</span>
      <div class="div-holder" />
      <button class="light-green-btn btn-modify-psw" @click="editBaseInfo(1)">
        修改密码
      </button>
    </div>

    <!-- 基本信息展示区域 -->
    <div class="second-line-div">
      <div class="single-item">
        <span class="secon-line-hint">用户名</span>
        <input class="input-css" v-model="baseInfo.accountName" disabled />
      </div>

      <div class="single-item">
        <span class="secon-line-hint">姓名</span>
        <input class="input-css" v-model="baseInfo.username" disabled />
      </div>

      <div class="single-item">
        <div class="div-holder" />
        <span class="secon-line-hint">联系电话</span>
        <input class="input-css" v-model="baseInfo.phone" disabled />
      </div>
      
      <div class="single-item">
        <span class="secon-line-hint">系统角色</span>
        <input class="input-css" v-model="baseInfo.roleNames" disabled />
      </div>

      <div class="single-item">
        <span class="secon-line-hint">电子邮箱</span>
        <input class="input-css" v-model="baseInfo.email" disabled />
      </div>

      <div class="single-item">
        <div class="div-holder" />
        <span class="secon-line-hint">注册时间</span>
        <input class="input-css" v-model="baseInfo.createdTime" disabled />
      </div>
    </div>

    <!-- 分割线 -->
    <div class="deliver" />
    
    <!-- 账号管理标签页 -->
    <div style="margin-bottom: 28px">
      <el-tabs v-model="activeName" @tab-click="handleTabChange">
        <el-tab-pane label="登录相关账号" name="first" :key="'first'">
          <div class="card-container">
            <div class="card-div">
              <img class="icon" src="@/assets/imgs/icon_user.png" alt="账号图标" />
              <span class="tap-secon-line-hint-f ml10">账号</span>
              <input class="input-css" v-model="baseInfo.accountName" disabled />
              <span class="second-line-final-hint">系统自动生成，可用于登录</span>
              <div class="div-holder" />
            </div>
            
            <div class="card-div">
              <img class="icon" src="@/assets/imgs/icon_mobile.png" alt="手机图标" />
              <span class="tap-secon-line-hint-f ml10">手机号</span>
              <input class="input-css" v-model="baseInfo.phone" disabled />
              <span class="second-line-final-hint">绑定手机号，可用于登录、重置密码或其他安全验证</span>
              <div class="div-holder" />
              <button class="normal-white-btn btn-modify-head" @click="editBaseInfo(3)">
                修改
              </button>
            </div>
            
            <div class="card-div">
              <img class="icon" src="@/assets/imgs/icon_email.png" alt="邮箱图标" />
              <span class="tap-secon-line-hint-f ml10">邮箱</span>
              <input class="input-css" v-model="baseInfo.email" disabled />
              <span class="second-line-final-hint">绑定邮箱，可用于登录、重置密码或其他安全验证</span>
              <div class="div-holder" />
              <button class="light-green-btn btn-modify-psw" @click="editBaseInfo(4)">
                {{ baseInfo.email && baseInfo.email !== '--' ? '修改' : '绑定' }}
              </button>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 交易账号相关 -->
        <el-tab-pane label="交易相关账号" name="second" :key="'second'">
          <div class="card-container">
            <el-table
              :header-cell-style="headerCellStyle"
              :show-header="true"
              :row-style="{ height: '64px' }"
              :cell-style="cellStyle"
              style="width: 100%"
              :row-class-name="tableRowClassName"
              :data="cardContainerList"
              row-key="id"
              :tree-props="{
                children: 'accountInfoList',
                hasChildren: 'hasChildren',
              }"
              v-loading="tableLoading"
            >
              <el-table-column
                label="平台"
                align="left"
                min-width="110"
                prop="name"
              ></el-table-column>

              <el-table-column
                label="账号"
                align="left"
                min-width="60"
                prop="accountName"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.accountName || "--" }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="账户状态"
                align="left"
                min-width="56"
                prop="accountStatusName"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.accountStatusName || "--" }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="最近登录"
                align="left"
                min-width="120"
                prop="loginTime"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.loginTime || "--" }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="绑定时间"
                align="left"
                min-width="120"
                prop="bindingTime"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.bindingTime || "--" }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="操作"
                width="auto"
                align="center"
                min-width="124"
              >
                <template slot-scope="scope">
                  <a
                    v-if="scope.row.is_disable === 1"
                    class="list-green-text"
                    @click="addAccountUser(scope.row)"
                  >
                    添加账号
                  </a>
                  <a
                    v-if="scope.row.is_disable === 0"
                    class="list-blue-text"
                    style="margin-left: 10px"
                    @click="copy(scope.row.accountName)"
                  >
                    复制账号
                  </a>
                  <a
                    v-if="scope.row.is_disable === 0"
                    style="margin-left: 10px"
                    class="list-red-text mgn-r-16"
                    @click="unboundWeChat(scope.row, scope.row.id, scope.$index)"
                  >
                    解绑
                  </a>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 修改密码弹窗 -->
    <el-dialog title="修改密码" :visible.sync="padShow" width="40%" :close-on-click-modal="false">
      <el-form
        label-position="left"
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            type="password"
            v-model="ruleForm.oldPassword"
            autocomplete="off"
            placeholder="请输入原密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            type="password"
            v-model="ruleForm.newPassword"
            autocomplete="off"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="重复新密码" prop="isCheckPass">
          <el-input
            type="password"
            v-model="ruleForm.isCheckPass"
            placeholder="请确认新密码"
          ></el-input>
        </el-form-item>
        <div class="btn-box">
          <div></div>
          <div class="btn-close" @click="editBaseInfo(1)">取消</div>
          <div class="btn-true" @click="putAccountPwd">保存</div>
        </div>
      </el-form>
    </el-dialog>

    <!-- 修改手机号弹窗 -->
    <el-dialog title="修改绑定的手机号" :visible.sync="ephShow" width="40%" :close-on-click-modal="false">
      <el-form
        label-position="left"
        :model="phoForm"
        status-icon
        :rules="rulePhoForm"
        ref="phoForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="新手机号" prop="newPhone">
          <el-input
            type="number"
            v-model="phoForm.newPhone"
            autocomplete="off"
            placeholder="请输入新手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="checkCode">
          <el-input
            type="number"
            v-model="phoForm.checkCode"
            autocomplete="off"
            placeholder="请输入验证码"
          >
            <a
              style="color: #24a776"
              v-if="times > 0"
              slot="append"
            >
              {{ times < 10 ? "0" + times : times }}秒
            </a>
            <a
              style="color: #24a776"
              v-else
              @click="sendCodeSet(60)"
              slot="append"
            >
              发送验证码
            </a>
          </el-input>
        </el-form-item>

        <div class="btn-box">
          <div></div>
          <div class="btn-close" @click="editBaseInfo(3)">取消</div>
          <div class="btn-true" @click="putAccountPhone">保存</div>
        </div>
      </el-form>
    </el-dialog>

    <!-- 绑定/修改邮箱弹窗 -->
    <el-dialog 
      :title="baseInfo.email && baseInfo.email !== '--' ? '修改邮箱' : '绑定邮箱'" 
      :visible.sync="emShow" 
      width="40%" 
      :close-on-click-modal="false"
    >
      <el-form
        label-position="left"
        :model="emailForm"
        status-icon
        :rules="emailFormRules"
        ref="emailFormRef"
        label-width="100px"
        class="demo-ruleForm text-f-ppc"
      >
        <el-form-item class="table-l" label="登录密码" prop="emailFormPassword">
          <el-input
            type="password"
            v-model="emailForm.emailFormPassword"
            autocomplete="off"
            placeholder="请输入登录密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="table-l text-f-ppc" label="邮箱" prop="email">
          <el-input
            type="text"
            v-model="emailForm.email"
            autocomplete="off"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        
        <div class="btn-box">
          <div></div>
          <div class="btn-close" @click="editBaseInfo(4)">取消</div>
          <div class="btn-true" @click="putAccountSendEmail">保存</div>
        </div>
      </el-form>
    </el-dialog>

    <!-- 添加交易账户弹窗 -->
    <el-dialog title="添加交易账户" :visible.sync="carbonUploadDlg" width="40%" :close-on-click-modal="false">
      <div class="content-div">
        <el-form
          label-position="left"
          ref="addUserFromRef"
          :rules="addUserFromRules"
          :model="addUserFrom"
          style="width: 100%"
        >
          <el-form-item prop="carbonExchangeId" label-width="20%">
            <label slot="label">交易所<span style="color: red">*</span></label>
            <el-select
              v-model="addUserFrom.carbonExchangeId"
              placeholder="请选择交易所"
              clearable
              style="width: 100%"
            >
              <el-option 
                v-for="item in exchangeList" 
                :key="item.value"
                :label="item.label" 
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="accountName" label-width="20%">
            <label slot="label">账号名<span style="color: red">*</span></label>
            <el-input
              v-model="addUserFrom.accountName"
              placeholder="请输入账号名"
            />
          </el-form-item>

          <el-form-item label-width="20%">
            <label slot="label">账户凭证<span style="color: red">*</span></label>
            <el-upload
              class="upload-demo"
              ref="upload2"
              :action="upLoadParam.url"
              :file-list="tranFileList"
              :auto-upload="true"
              :headers="{ token: upLoadParam.token }"
              :on-change="handleTranChange"
              :on-remove="removeFileList"
              :on-success="upLoadParamTranFile"
              :on-preview="tranFilehandlePreview"
            >
              <div class="light-green-btn line-h-32">上传</div>
            </el-upload>
          </el-form-item>

          <el-form-item label="备注" label-width="20%">
            <el-input
              type="textarea"
              placeholder="请输入备注内容"
              rows="3"
              v-model="addUserFrom.remarks"
              class="input-mark"
            ></el-input>
          </el-form-item>
        </el-form>

        <div slot="footer" class="footer-btn">
          <div></div>
          <div @click="clickSubmit" class="light-green-btn line-h-32">
            提交
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 头像上传弹窗 - 使用飞书上传逻辑 -->
    <el-dialog title="更换头像" :visible.sync="avatarDialogVisible" width="30%" :close-on-click-modal="false">
      <el-form
      ref="avatarUploadFormRef"  
      :model="avatarForm"        
      label-width="20%"    >   
     
      <div v-if="upLoadParam && upLoadParam.url" class="avatar-upload-container">
        <el-form-item label="头像文件" label-width="20%">
          <el-upload
            class="upload-demo"
            ref="avatarUpload"
            :action="upLoadParam.url"  
            :headers="{ token: upLoadParam.token }"  
            :file-list="avatarFileList"
            :auto-upload="true"
            :on-change="handleAvatarFileChange" 
            :on-remove="removeAvatarFile"
            :on-success="handleAvatarUploadSuccess"  
            :on-preview="handleAvatarPreview"
            :before-upload="beforeAvatarUpload"
            accept="image/jpeg,image/png" 
            :limit="1"  
          >
            <div class="light-green-btn line-h-32">上传</div>
          </el-upload>
        </el-form-item>
        
        <!-- 预览区域 -->
        <div v-if="avatarPreviewUrl" class="avatar-preview-container">
          <img :src="avatarPreviewUrl" class="preview-avatar" alt="头像预览" />
        </div>
        
        <div class="avatar-hint">支持JPG、PNG格式，建议尺寸100x100px，文件大小不超过2MB</div>
      </div>
      <div v-else class="avatar-loading">头像上传服务加载中...</div>
      </el-form>  
      <div slot="footer" class="btn-box">
        <div class="btn-close" @click="avatarDialogVisible = false">取消</div>
        <div class="btn-true" @click="confirmAvatarChange">确认更换</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getListByTenant,
  getFeiShuUpLoadProjectParams,  // 飞书上传参数获取方法
  putAddExchangeAccount,
  getAccoutBaseInfo,
  putAccountUpdatePassword,
  putAccountSend,
  putAccountUpdatePhone,
  getAccoutUpdateCode,
  getAccoutUpdateAvatar,
  getUpLoadFileParams,
} from "@/api/tenant";
import { openUrlInNewWindow } from '@/libs/OpenHelper';
import { putCarbonExchangeUnbind } from "@/api/carbonAssetApi";
import { getTenantList } from "@/api/systemadmin";
import { cursor } from "@/libs/element-table";
import Cookies from "js-cookie";
import md5 from "js-md5";

export default {
  name: "UserProfile",
  components: {},
  data() {
    // 表单验证规则
    const validateOldPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入原密码"));
      } else {
        callback();
      }
    };
    
    const validateNewPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入新密码"));
      } else {
        callback();
      }
    };
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    
    const validateNewPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入新手机号"));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error("请输入有效的手机号"));
      } else {
        callback();
      }
    };
    
    const validateCheckCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    
    const validateEmail = (rule, value, callback) => {
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if (!value) {
        callback(new Error("请输入邮箱"));
      } else if (!emailReg.test(value)) {
        callback(new Error("请输入有效的邮箱地址"));
      } else {
        callback();
      }
    };
    
    const validateEmailPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入登录密码"));
      } else {
        callback();
      }
    };

    return {
      // 上传参数配置 - 只保留飞书上传参数
      upLoadParam: {}, // 飞书上传参数（与交易凭证共用）
      
      // 用户信息
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      baseInfo: {
        id: "--",
        accountName: "--",
        username: "--",
        phone: "--",
        role: "--",
        email: "--",
        createdTime: "--",
        tenantId: "--",
        roleNames: "",
        avatar: "",
      },
      avatarForm: {}, 
      // 弹窗控制
      padShow: false,        // 修改密码弹窗
      emShow: false,         // 邮箱弹窗
      ephShow: false,        // 手机号弹窗
      dialogTip: false,      // 提示弹窗
      carbonUploadDlg: false,// 添加交易账户弹窗
      avatarDialogVisible: false, // 头像上传弹窗
      
      // 标签页控制
      activeName: "first",
      
      // 修改密码表单
      ruleForm: {
        id: 0,
        oldPassword: "",
        newPassword: "",
        isCheckPass: "",
      },
      
      // 手机号修改表单
      phoForm: {
        id: 0,
        accountName: "",
        email: "",
        phone: "",
        newPhone: "",
        checkCode: "",
      },
      
      // 邮箱表单
      emailForm: {
        email: "",
        emailFormPassword: "",
      },
      
      // 表单验证规则
      rulePhoForm: {
        newPhone: [{ validator: validateNewPhone, trigger: "blur" }],
        checkCode: [{ validator: validateCheckCode, trigger: "blur" }],
      },
      emailFormRules: {
        email: [{ validator: validateEmail, trigger: "blur" }],
        emailFormPassword: [{ validator: validateEmailPassword, trigger: "blur" }],
      },
      rules: {
        oldPassword: [{ validator: validateOldPassword, trigger: "blur" }],
        newPassword: [{ validator: validateNewPassword, trigger: "blur" }],
        isCheckPass: [{ validator: validateConfirmPassword, trigger: "blur" }],
      },
      addUserFromRules: {
        carbonExchangeId: [{ required: true, message: "请选择交易所", trigger: "change" }],
        accountName: [{ required: true, message: "请输入账号名", trigger: "blur" }],
      },
      
      // 头像上传相关 - 与交易凭证上传逻辑保持一致
      avatarFileList: [],    // 头像文件列表（仅保留1个文件）
      avatarFeiShuUrl: "",   // 头像的飞书文件地址
      avatarPreviewUrl: "",  // 头像预览图
      
      // 其他数据
      byTenantList: [],       // 碳交易所列表
      fileList: [],
      tranFileList: [],       // 账户凭证文件列表
      tranFileUrl: "",        // 账户凭证URL
      fileListurl: "",
      times: 0,               // 验证码倒计时
      tableLoading: false,    // 表格加载状态
      
      // 添加交易账号表单
      addUserFrom: {
        carbonExchangeName: "",
        accountName: "",
        accountStatus: 0,
        accountType: 0,
        bindingTime: "",
        brokerId: 0,
        carbonAmount: 0,
        carbonExchangeId: null,
        ccerAmount: 0,
        createdTime: "",
        creatorId: 0,
        cookie: "",
        id: 0,
        loginTime: "",
        password: "",
        remarks: "",
        tenantId: 0,
        updatedId: 0,
        updatedTime: "",
      },
      user : JSON.parse(localStorage.getItem('user') || '{}'),
      accountNameList: [],    // 账户列表
      exchangeList: [],       // 交易所列表
      cardContainerList: [],  // 交易账户列表数据
    };
  },
  
  mounted() {
    // 初始化页面数据
    this.getBaseInfo();
    this.getListByTenantInfo();
    this.initUploadParams();
    
    // 处理路由参数
    if (this.$route && this.$route.query && this.$route.query.path) {
      this.activeName = this.$route.query.path;
    }
  },
  
  methods: {
    // 初始化上传参数 - 只初始化飞书上传参数
    initUploadParams() {
      this.upLoadParam = getFeiShuUpLoadProjectParams();
    },
    
    // 表格样式
    headerCellStyle() {
      return {
        background: '#F2F5F7',
        border: '0px solid #DDDDDD',
        color: '#242B35',
        height: '64px',
      };
    },
    
    cellStyle(data) {
      cursor(data);
      return data.row.is_disable 
        ? "padding-left:16px;cursor:pointer;" 
        : "padding-left:16px;cursor:default;";
    },
    
    tableRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 0 ? "warning-row" : "warning-row";
    },
    
    // 复制功能
    copy(text) {
      if (!text) {
        return this.$message.warning("未绑定账号");
      }
      
      const oInput = document.createElement("input");
      oInput.value = text;
      document.body.appendChild(oInput);
      oInput.select();
      document.execCommand("Copy");
      this.$message.success("复制成功");
      oInput.remove();
    },
    
    // 头像上传相关 - 复用飞书上传逻辑
    openAvatarUpload() {
      // 打开弹窗时清空文件列表和临时URL
      this.avatarFileList = [];
      this.avatarPreviewUrl = "";
      this.avatarFeiShuUrl = "";
      this.avatarDialogVisible = true;
    },
    
    // 头像文件变更处理：限制仅保留1个文件 + 生成前端预览图
    handleAvatarFileChange(file, fileList) {
      // 仅保留最后1个选择的文件（与交易凭证逻辑一致）
      this.avatarFileList = fileList.slice(-1);
      // 生成前端预览图
      if (file.raw) {
        this.avatarPreviewUrl = URL.createObjectURL(file.raw);
      }
    },
    
    // 移除头像文件
    removeAvatarFile() {
      this.avatarFileList = [];
      this.avatarPreviewUrl = "";
      this.avatarFeiShuUrl = "";
    },
    
    // 预览头像
    handleAvatarPreview(file) {
      if (file && file.response && file.response.msg) {
        this.avatarPreviewUrl = file.response.msg;
      }
    },
    
    // 头像上传前验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    
    // 头像上传飞书成功回调：保存飞书返回的地址（与交易凭证逻辑一致）
    handleAvatarUploadSuccess(response) {
      if (response && response.code === 200) {
        this.avatarFeiShuUrl = response.msg; // 保存头像的飞书地址
        this.avatarPreviewUrl = response.msg; // 显示预览
        this.$message.success('头像上传成功');
      } else {
        this.$message.error('头像上传飞书失败：' + (response.msg || "未知错误"));
      }
    },
    
    // 确认更换头像
    confirmAvatarChange() {
      if (!this.avatarFeiShuUrl) {
        return this.$message.warning('请上传头像图片');
      }
      const updateData = {
        avatar: this.avatarFeiShuUrl, // 原有头像飞书地址
        id: this.user.tenantId   // 新增租户ID，后端要求的参数
      };
      // 调用接口将飞书地址保存到业务系统
      getAccoutUpdateAvatar(updateData)
        .then(res => {
          if (res.code === 200) {
            this.$message.success('头像更新成功');
            this.baseInfo.avatar = this.avatarFeiShuUrl;
            // 更新本地存储的用户信息
            this.user.avatar = this.avatarFeiShuUrl;
            localStorage.setItem("user", JSON.stringify(this.user));
            this.avatarDialogVisible = false;
          } else {
            this.$message.error(res.msg || '头像更新失败');
          }
        })
        .catch(err => {
          console.error('头像更新失败:', err);
          this.$message.error('头像更新失败');
        });
    },
    
    // 账户凭证上传相关（交易凭证）
    upLoadParamTranFile(response) {
      if (response && response.code === 200) {
        this.tranFileUrl = response.msg;
      } else {
        this.$message.error('文件上传失败');
      }
    },
    
    // 验证码倒计时
    sendCodeSet(num) {
      if (!this.phoForm.newPhone) {
        return this.$message.warning("请输入新手机号");
      }
      
      if (this.phoForm.newPhone === this.baseInfo.phone) {
        return this.$message.warning("新手机号与当前绑定的手机号一致!");
      }
      
      // 开始倒计时
      this.times = num;
      const timer = setInterval(() => {
        if (this.times > 0) {
          this.times--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
      
      // 发送验证码
      getAccoutUpdateCode(this.phoForm.newPhone)
        .catch(err => {
          clearInterval(timer);
          this.times = 0;
          console.error('发送验证码失败:', err);
          this.$message.error('发送验证码失败，请重试');
        });
    },
    
    // 获取用户基本信息
    getBaseInfo() {
      const javaInfoStr = Cookies.get('JavaInfo');
      if (!javaInfoStr) {
        return;
      }
      
      this.tableLoading = true;
      getAccoutBaseInfo(javaInfoStr)
        .then(res => {
         if (res && res.code === 200 && res.data) {
            this.baseInfo = {
              ...res.data,
              email: res.data.email || "--",
              username: res.data.username || "--",
            };
          }
        })
        .catch(err => {
          console.error("获取用户基本信息失败：", err);
          this.$message.error('获取用户信息失败');
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    
    // 获取交易账户列表
    getListByTenantInfo() {
      const javaInfoStr = Cookies.get('JavaInfo');
      if (!javaInfoStr) {
        return;
      }
      
      this.tableLoading = true;
      getListByTenant(javaInfoStr)
        .then(res => {
          if (res && res.code === 200 && Array.isArray(res.data)) {
            // 处理返回数据
            const processedData = res.data.map(item => {
              const processedItem = {
                ...item,
                is_disable: 1,
              };
              
              // 处理子账户信息
              if (processedItem.accountInfoList && processedItem.accountInfoList.length) {
                processedItem.accountInfoList = processedItem.accountInfoList.map((subItem, index) => ({
                  ...subItem,
                  accountName: `账号${index + 1}`,
                  is_disable: 0,
                }));
              }
              
              return processedItem;
            });
            
            this.cardContainerList = processedData;
            
            // 构建交易所下拉列表
            this.exchangeList = res.data.map(item => ({
              value: item.id,
              label: item.name,
            }));
          }
        })
        .catch(err => {
          console.error("获取交易账户列表失败：", err);
          this.$message.error('获取交易账户列表失败');
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    
    // 标签页切换处理
    handleTabChange(tab) {
      // 可以在这里添加标签页切换时的逻辑
    },
    
    // 弹窗控制
    editBaseInfo(type) {
      switch (type) {
        case 1:
          this.ruleForm = {
            id: 0,
            oldPassword: "",
            newPassword: "",
            isCheckPass: "",
          };
          this.padShow = !this.padShow;
          break;
        case 3:
          this.phoForm = {
            ...this.phoForm,
            newPhone: "",
            checkCode: "",
          };
          this.times = 0;
          this.ephShow = !this.ephShow;
          break;
        case 4:
          this.emailForm = {
            email: this.baseInfo.email !== '--' ? this.baseInfo.email : '',
            emailFormPassword: "",
          };
          this.emShow = !this.emShow;
          break;
        case 5:
          this.carbonUploadDlg = !this.carbonUploadDlg;
          break;
        default:
          break;
      }
    },
    
    // 修改密码提交
    putAccountPwd() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          const datas = {
            id: this.baseInfo.id,
            newPassword: md5(this.ruleForm.newPassword),
            oldPassword: md5(this.ruleForm.oldPassword),
          };
          
          putAccountUpdatePassword(datas)
            .then(res => {
              if (res.code === 200) {
                this.$message.success("修改成功");
                this.editBaseInfo(1);
              } else {
                this.$message.error(res.msg || '修改失败');
              }
            })
            .catch(err => {
              console.error("修改密码失败：", err);
              this.$message.error('修改密码失败');
            });
        }
      });
    },
    
    // 修改手机号提交
    putAccountPhone() {
      this.$refs.phoForm.validate(valid => {
        if (valid) {
          const phoDatas = {
            id: this.baseInfo.id,
            phone: this.phoForm.newPhone,
            code: this.phoForm.checkCode,
          };
          
          putAccountUpdatePhone(phoDatas)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg || '修改成功');
                this.getBaseInfo();
                this.editBaseInfo(3);
              } else {
                this.$message.error(res.msg || '修改失败');
              }
            })
            .catch(err => {
              console.error("修改手机号失败：", err);
              this.$message.error('修改手机号失败');
            });
        }
      });
    },
    
    // 绑定/修改邮箱提交
    putAccountSendEmail() {
      this.$refs.emailFormRef.validate(valid => {
        if (valid) {
          const datas = {
            email: this.emailForm.email,
            id: this.user.accountId,
            password: md5(this.emailForm.emailFormPassword),
          };
          
          putAccountSend(datas)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg || '操作成功');
                this.getBaseInfo();
                this.emShow = false;
              } else {
                this.$message.error(res.msg || '操作失败');
              }
            })
            .catch(err => {
              console.error("邮箱操作失败：", err);
              this.$message.error('邮箱操作失败');
            });
        }
      });
    },
    
    // 交易账户凭证上传相关
    tranFilehandlePreview(file) {
      if (file && file.response && file.response.msg) {
        openUrlInNewWindow(file.response.msg);
      }
    },
    
    handleTranChange(file, fileList) {
      this.tranFileList = fileList.slice(-1);
    },
    
    removeFileList() {
      this.tranFileList = [];
      this.tranFileUrl = "";
    },
    
    // 解绑交易账户
    unboundWeChat(row, id) {
      if (!id) {
        return this.$message.warning("未绑定账号");
      }
      
      this.$confirm(`确定解绑交易账户？`, "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          putCarbonExchangeUnbind(id)
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.msg || '解绑成功');
                this.getListByTenantInfo();
              } else {
                this.$message.error(res.msg || '解绑失败');
              }
            })
            .catch(err => {
              console.error("解绑交易账户失败：", err);
              this.$message.error('解绑失败');
            });
        })
        .catch(() => {
          // 取消操作
        });
    },
    
    // 添加交易账户
    addAccountUser(row) {
      this.addUserFrom = {
        ...this.addUserFrom,
        accountName: "",
        remarks: "",
        carbonExchangeId: row.is_disable ? row.id : row.carbonExchangeId,
      };
      this.tranFileList = [];
      this.tranFileUrl = "";
      this.editBaseInfo(5);
    },
    
    // 提交添加交易账户
    clickSubmit() {
      this.$refs.addUserFromRef.validate(valid => {
        if (valid) {
          if (!this.tranFileList || this.tranFileList.length === 0) {
            return this.$message.warning("请上传账户凭证！");
          }
          
          const info = JSON.parse(Cookies.get("JavaInfo") || '{}');
          const datas = {
            accountName: this.addUserFrom.accountName,
            carbonExchangeId: this.addUserFrom.carbonExchangeId,
            remarks: this.addUserFrom.remarks,
            tenantId: parseInt(info.accountId || 0),
            accountCredentials: this.tranFileUrl,
          };
          
          putAddExchangeAccount(datas)
            .then(res => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.getListByTenantInfo();
                this.editBaseInfo(5);
              } else {
                this.$message.error(res.msg || '操作失败');
              }
            })
            .catch(err => {
              console.error("添加交易账户失败：", err);
              this.$message.error('添加交易账户失败');
            });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.root {
  padding: 0 30px;
  background: #ffffff;
  box-shadow: 0px 2px 8px 0px #eaf0f3;
  border-radius: 8px;
  margin: 28px;
  overflow: auto;
}

.header {
  display: flex;
  flex-direction: row;
  padding-top: 40px;
  align-items: center;
}

// 头像样式
.avatar-container {
  position: relative;
  width: 56px;
  height: 56px;
  margin-right: 20px;
  cursor: pointer;
  
  .head-icon {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    object-fit: cover;
  }
  
  .avatar-placeholder {
    width: 56px;
    height: 56px;
    border-radius: 50%;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #c0c4cc;
    font-size: 24px;
  }
  
  .avatar-upload-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    opacity: 0;
    transition: opacity 0.3s;
    font-size: 12px;
    
    i {
      margin-bottom: 4px;
      font-size: 16px;
    }
  }
  
  &:hover .avatar-upload-overlay {
    opacity: 1;
  }
}

.baseInfo {
  font-size: 18px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #242b35;
}

.div-holder {
  flex-grow: 1;
}

.btn-modify-psw, .btn-modify-head {
  cursor: pointer;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-modify-psw {
  background-color: #26b581;
  color: white;
  
  &:hover {
    background-color: #20a068;
  }
}

.btn-modify-head {
  background-color: white;
  color: #26b581;
  border: 1px solid #26b581;
  
  &:hover {
    background-color: #f5faf7;
  }
}

.second-line-div {
  display: grid;
  grid: auto / auto auto auto;
  grid-gap: 20px;
  margin-top: 30px;
}

.single-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.secon-line-hint {
  width: 80px;
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #3a4063;
  margin-right: 20px;
}

.input-css {
  flex: 1;
  height: 36px;
  padding: 0 12px;
  border: 1px solid #e3e7eb;
  border-radius: 4px;
  background-color: #f5f7fa;
  color: #808ea5;
  font-size: 14px;
  
  &:disabled {
    cursor: not-allowed;
  }
}

.deliver {
  margin: 40px 0;
  height: 1px;
  border: 1px dashed #dadee5;
}

.tap-secon-line-hint-f {
  text-align: center;
  align-self: center;
  width: 64px;
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #3a4063;
}

.ml10 {
  margin-left: 10px;
}

.card-container {
  display: flex;
  flex-direction: column;
}

.card-div {
  margin-top: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #f2f3f5;
  
  &:last-child {
    border-bottom: none;
  }
}

.icon {
  width: 18px;
  height: 18px;
}

.second-line-final-hint {
  margin: 0 20px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #5e6c84;
  flex: 1;
}

// 弹窗按钮样式
.btn-box {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  
  .btn-close, .btn-true {
    width: 80px;
    height: 32px;
    border-radius: 2px;
    margin-left: 10px;
    cursor: pointer;
    text-align: center;
    line-height: 32px;
    font-size: 14px;
  }
  
  .btn-close {
    border: 1px solid #d0d5de;
    color: #3a4063;
    
    &:hover {
      background-color: #f5f7fa;
    }
  }
  
  .btn-true {
    background: #26b581;
    color: white;
    
    &:hover {
      background-color: #20a068;
    }
  }
}

// 操作链接样式
.list-green-text {
  color: #26b581;
  cursor: pointer;
  
  &:hover {
    color: #20a068;
    text-decoration: underline;
  }
}

.list-blue-text {
  color: #228be6;
  cursor: pointer;
  
  &:hover {
    color: #1d77d5;
    text-decoration: underline;
  }
}

.list-red-text {
  color: #fa5252;
  cursor: pointer;
  
  &:hover {
    color: #e04646;
    text-decoration: underline;
  }
}

.mgn-r-16 {
  margin-right: 16px;
}

// 头像上传弹窗样式
.avatar-upload-container {
  padding: 20px 0;
  
  .avatar-preview-container {
    margin-top: 15px;
    text-align: center;
  }
  
  .preview-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    border: 1px solid #e3e7eb;
  }
  
  .avatar-hint {
    margin-top: 15px;
    color: #808ea5;
    font-size: 12px;
  }
  
  .upload-demo {
    margin-top: 5px;
  }
}

.avatar-loading {
  padding: 40px;
  text-align: center;
  color: #808ea5;
}

// 添加交易账户弹窗样式
.content-div {
  .item-div {
    margin-bottom: 15px;
  }
  
  .input-mark {
    width: 100%;
  }
  
  .upload-demo {
    margin-top: 5px;
  }
}

.footer-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.line-h-32 {
  line-height: 32px;
  text-align: center;
}

.light-green-btn {
  background-color: #26b581;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #20a068;
  }
}

.normal-white-btn {
  background-color: white;
  color: #26b581;
  border: 1px solid #26b581;
  border-radius: 4px;
  padding: 0 16px;
  cursor: pointer;
  transition: all 0.2s;
  
  &:hover {
    background-color: #f5faf7;
  }
}

// 标签页样式
::v-deep .el-tabs {
  .el-tabs__nav {
    width: calc(100% - 200px);
  }
  
  .el-tabs__item.is-active {
    color: #26a872;
  }
  
  .el-tabs__item:hover {
    color: #26a872;
  }
  
  .el-tabs__active-bar.is-top {
    background: #26a872;
  }
  
  .el-tabs__item {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #5e6c84;
  }
}

// 表格样式
::v-deep .el-table {
  th.el-table__cell > .cell {
    padding-left: 16px;
  }
  
  .el-table__row {
    transition: background-color 0.2s;
    
    &:hover > td {
      background-color: #f5faf7 !important;
    }
  }
}

// 表单样式覆盖
::v-deep .el-dialog__title {
  font-size: 20px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #3a4063;
  line-height: 20px;
}

::v-deep .el-form-item__label {
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #3a4063;
}

::v-deep .el-input__inner {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #808ea5;
}

::v-deep .el-select__input {
  color: #808ea5;
}
</style>
